import tkinter as tk
from tkinter import font
from src.tts import TextToSpeech
import keyboard
import random

class Application:
    def __init__(self):
        self.root = tk.Tk()
        self.setup_window()
        self.setup_bindings()
        self.tts = TextToSpeech()
        self.words = self.load_words()
        self.buttons = []
        self.candidate_words = []  # 9个待选字
        self.target_word = ""      # 待学字
        self.score = 0            # 当前积分
        self.setup_ui()
        self.start_new_round()
        
    def load_words(self):
        """从words.txt加载汉字列表"""
        with open('assets/words.txt', 'r', encoding='utf-8') as f:
            # 过滤掉注释行和空行
            return [line.strip() for line in f if line.strip() and not line.startswith('#')]
    
    def setup_window(self):
        # 设置窗口标题
        self.root.title("小孩认字")
        # 移除窗口装饰（包括菜单栏和工具栏）
        self.root.overrideredirect(True)
        # 设置窗口最大化
        self.root.state('zoomed')
        # 设置背景色为白色
        self.root.configure(bg='white')
        # 设置窗口置顶
        self.root.attributes('-topmost', True)
        
    def setup_ui(self):
        # 创建主容器，使用网格布局
        main_container = tk.Frame(self.root, bg='white')
        main_container.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        
        # 顶部区域 - 积分显示
        top_frame = tk.Frame(main_container, bg='white')
        top_frame.pack(fill=tk.X, pady=(0, 40))
        
        self.score_label = tk.Label(
            top_frame,
            text="连续答对: 0",
            font=('SimHei', 32),
            bg='white'
        )
        self.score_label.pack()
        
        # 中间区域 - 按钮网格
        button_frame = tk.Frame(main_container, bg='white')
        button_frame.pack(expand=True)
        
        # 创建3x3按钮网格
        for i in range(3):
            button_frame.grid_rowconfigure(i, weight=1)
            for j in range(3):
                button_frame.grid_columnconfigure(j, weight=1)
                btn = tk.Button(
                    button_frame,
                    text="",
                    font=('SimHei', 48),
                    width=3,
                    height=1,
                    command=lambda x=i, y=j: self.check_answer(x * 3 + y)
                )
                btn.grid(row=i, column=j, padx=15, pady=15)
                self.buttons.append(btn)
        
        # 底部区域 - "再读一遍"按钮
        bottom_frame = tk.Frame(main_container, bg='white')
        bottom_frame.pack(fill=tk.X, pady=(40, 0))
        
        self.repeat_button = tk.Button(
            bottom_frame,
            text="再读一遍",
            font=('SimHei', 32),
            command=self.speak_question,
            bg='lightblue',
            width=8,
            height=1
        )
        self.repeat_button.pack()
    
    def speak_question(self):
        """朗读问题"""
        self.tts.speak(f"请问小朋友哪一个字是{self.target_word}")
    
    def start_new_round(self):
        """开始新一轮游戏"""
        # 获取所有不重复的字
        unique_words = list(set(self.words))
        
        # 随机选择9个待选字
        if len(unique_words) >= 9:
            self.candidate_words = random.sample(unique_words, 9)
        else:
            # 如果不重复的字不足9个，提示错误
            raise ValueError("字表中不重复的字少于9个，请在words.txt中添加更多不同的字")
        
        # 从9个待选字中随机选择一个作为待学字
        self.target_word = random.choice(self.candidate_words)
        
        # 朗读问题
        self.speak_question()
        
        # 随机排列9个待选字到按钮上
        random.shuffle(self.candidate_words)
        for btn, word in zip(self.buttons, self.candidate_words):
            btn.config(text=word)
    
    def update_score_display(self):
        """更新积分显示"""
        self.score_label.config(text=f"连续答对: {self.score}")
        
    def check_answer(self, button_index):
        """检查答案"""
        selected_word = self.buttons[button_index]['text']
        if selected_word == self.target_word:
            self.tts.speak("答对了")
            self.score += 1
            self.update_score_display()
            
            if self.score >= 3:
                # 达到3分，播放祝贺语音并退出
                self.tts.speak("太棒了！你已经连续答对三次了！")
                self.root.iconify()  # 最小化窗口
                self.score = 0
                self.root.after(300000, self.root.deiconify)  # 5分钟后显示窗口
            else:
                # 继续游戏
                self.root.after(1000, self.start_new_round)
        else:
            self.tts.speak("答错了")
            # 答错时重置积分
            self.score = 0
            self.update_score_display()
            # 继续新一轮
            self.root.after(1000, self.start_new_round)
        
    def setup_bindings(self):
        # 设置退出快捷键
        keyboard.add_hotkey('ctrl+shift+c', self.quit_app)
        
    def quit_app(self):
        self.root.quit()
        
    def run(self):
        self.root.mainloop() 